package longrise.phone.com.bjjt_henan.compensate;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.CoordUtil;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.android.util.IntenetUtil;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.UiUtils;
import longrise.phone.com.bjjt_henan.widget.HeNanDialog;

/**
 * 进入快处快赔的安全提示，Created by Administrator on 2016/5/12.
 */
public class SafeWarningView extends LFView implements View.OnClickListener, BDLocationListener {
    private Context context = null;
    private View view = null;
    private Button bt_safewarining_ensure;
    private Dialog processDialog;
    private BaseApplication mApplication;
    private LinearLayout hn_btn_back;
    private TextView tv_title;
    // 地图定位服务
    private LocationClient mLocationClient = null;
    private Dialog dialog;
    private boolean isSuccess = false;
    private HeNanDialog infoDialog;

    public SafeWarningView(Context c) {
        super(c);
        this.context = c;
        this.mApplication = (BaseApplication) c.getApplicationContext();
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {

    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
    }

    private void initView() {
        view = View.inflate(context, R.layout.view_safewarning, null);
        bt_safewarining_ensure = (Button) view.findViewById(R.id.bt_safewarining_ensure);
        hn_btn_back = (LinearLayout) view.findViewById(R.id.hn_btn_back);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText("安全提示");

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
//        option.setCoorType("gcj02");// 可选，默认gcj02，设置返回的定位结果坐标系，
        option.setCoorType("bd09ll");
        option.setScanSpan(3000);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);// 可选，默认false,设置是否使用gps
        option.setLocationNotify(true);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIgnoreKillProcess(true);// 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        // 开始定位
        mLocationClient = new LocationClient(context, option);
        mLocationClient.registerLocationListener(SafeWarningView.this);
        // 判断是否有网络连接
        if (IntenetUtil.getNetworkState(context) == IntenetUtil.NETWORN_NONE) {
            Toast.makeText(context, "没有网络连接", Toast.LENGTH_SHORT).show();
            return;
        }
        if (null != mLocationClient && !mLocationClient.isStarted()) {
            mLocationClient.start();
        }
        dialog = UiUtil.showProcessDialog(context, "获取位置中...");
    }

    private void regEvent(boolean b) {
        if (null != bt_safewarining_ensure) {
            bt_safewarining_ensure.setOnClickListener(b ? this : null);
        }

        if (null != hn_btn_back) {
            hn_btn_back.setOnClickListener(b ? this : null);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_safewarining_ensure:
                //进入溫馨提示
                //获取areaid，存入application中，暂时存死为"410101000000000000"
                if (!isSuccess) {//定位失败则重新定位
                    String latitude = mApplication.getLatitude();
                    String longitude = mApplication.getLongitude();
                    dialog = UiUtil.showProcessDialog(context, "获取位置中...");
//                    createAreaId(latitude, longitude, true);
                    getAreaId(latitude, longitude, true);
                    return;
                }
                PromptView promptview = new PromptView(context);
                FrameworkManager.getInstance().showNewForm(context, promptview);
                break;
            case R.id.hn_btn_back:
                closeForm();
                OnDestroy();
                break;
        }
    }

    /**
     * 获取areid，经纬度
     *
     * @param lat
     * @param lon
     */
    private void createAreaId(String lat, String lon, final boolean flag) {
        EntityBean bean = new EntityBean();
        // 经纬度
        bean.set("maplon", lon);
        bean.set("maplat", lat);
//        // 设备类型 0：Android 1：IOS
//        bean.set("device", 0);
//        // 菜单类型 0：出行 1：菜单
//        bean.set("menutype", 0);
        LoadDataManagerCar.getInstance(context).callService(null,
                ((BaseApplication) context.getApplicationContext()).getBaseServerUrl(),
                URLConstant.GETAREDID, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != dialog) {
                            dialog.cancel();
                        }
                        if (null != result) {
                            EntityBean bean = (EntityBean) result;
                            String restate = bean.getString("restate");
                            if ("1".equals(restate)) {
                                String areaId = bean.getString("data");
                                ((BaseApplication) context.getApplicationContext()).setAreaid(areaId);
                                isSuccess = true;
                                if (flag) {
                                    PromptView promptview = new PromptView(context);
                                    FrameworkManager.getInstance().showNewForm(context, promptview);
                                }
                            } else {
                                String redes = bean.getString("redes");
                                Toast.makeText(context, redes, Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(context, "数据加载失败，请检查网络是否连接", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != dialog) {
                            dialog.cancel();
                        }
                        Toast.makeText(context, "数据加载失败，请检查网络是否连接", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != dialog) {
                            dialog.cancel();
                        }
                    }
                });
    }

    /**
     * 定位回调方法
     */
    @Override
    public void onReceiveLocation(BDLocation location) {
        if (null != location) {
            String cityCode = location.getCityCode();
            if (!StringUtils.isEmpty(cityCode)) {
                // 经纬度
                mApplication.setLatitude(String.valueOf(location.getLatitude()));
                mApplication.setLongitude(String.valueOf(location.getLongitude()));
                // 详细地址
                mApplication.setAddress(location.getAddrStr());
                // 获取省和市等信息 add by huxin
                mApplication.setAddressbean(location.getAddress());
            }
            String latitude = mApplication.getLatitude();
            String longitude = mApplication.getLongitude();
            mApplication.setAddressbean(location.getAddress());
//            createAreaId(latitude, longitude,false);
            getAreaId(latitude, longitude, false);
        } else {
            if (null != dialog) {
                dialog.cancel();
            }
        }
        // 停止定位
        if (null != mLocationClient && mLocationClient.isStarted()) {
            mLocationClient.stop();
        }
    }

    private void getAreaId(String latitude, String longitude, final boolean flag) {
        String userflag = mApplication.getKckpName();
        String token = mApplication.getToken();
        ApiImpI.getInstance(context).getAreaId(longitude, latitude, userflag, token,
                new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        if (null != dialog) {
                            dialog.cancel();
                        }
                        if (!TextUtils.isEmpty(error)) {
                            UiUtil.showToast(context, error);
                        }
                    }

                    @Override
                    public void onSuccess(Object result) {
                        if (null != dialog) {
                            dialog.cancel();
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        if (TextUtils.equals(restate, "1")) {
                            EntityBean dataBean = bean.getBean("data");
                            if (null != dataBean) {
                                String isHN = dataBean.getString("IsHN");
//                                if (TextUtils.equals(isHN, "1")) {//定位地点在河南省内
                                String areaId = dataBean.getBean("position").getString("areaid");
                                ((BaseApplication) context.getApplicationContext()).setAreaid(areaId);
                                isSuccess = true;
                                if (flag) {
                                    PromptView promptview = new PromptView(context);
                                    FrameworkManager.getInstance().showNewForm(context, promptview);
                                }
//                                } else {
//                                    showInfoDialog();
//                                }
                                return;
                            }
                        }
                        String redes = bean.getString("redes");
                        Toast.makeText(context, redes, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //提示说明
    private void showInfoDialog() {
        if (null == infoDialog) {
            infoDialog = UiUtils.showSingleDialog(context, null, "抱歉，该应用暂时只处理河南省以内的车辆事故！",
                    "确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            closeForm();
                            OnDestroy();
                        }
                    });
        } else {
            infoDialog.show();
        }
    }

    @Override
    public void OnDestroy() {
        processDialog = null;
        dialog = null;
        if (null != infoDialog) {
            infoDialog.dismiss();
            infoDialog = null;
        }
        view = null;
        mLocationClient = null;
        super.OnDestroy();
    }
}
